import { match } from 'deep-replace';
import isNumber from 'is-number';
import { cloneDeep, isString, round, set } from 'lodash-es';

export const deepRound: (
  object: object,
  precision?: number | undefined,
) => object = (object, precision) => {
  object = cloneDeep(object);
  const valueTest = (value: any) => {
    return isNumber(value);
  };
  const propertyTest = null;
  const decorator = ({
    val,
    obj,
    prop,
  }: {
    val: any;
    obj: object;
    prop: string;
  }) => {
    let newVal: string | number;
    newVal = round(Number(val), precision);
    if (isString(val)) {
      newVal = String(newVal);
    }
    set(obj, prop, newVal);
  };
  match(object, valueTest, propertyTest, decorator);
  return object;
};
